//
//  OrderCashBackViewController.swift
//  FeastBooking
//
//  Created by Imon on 2017/11/16.
//  Copyright © 2017年 Imon. All rights reserved.
//

import UIKit
import RxSwift

class OrderCashBackViewController: UIViewController {
    
    var orderId: Int?
    var role: [RoleInOrder]?
    let authManager = AuthManager.share
    var cashBackVM: CashBackViewModel?
    let disposeBag = DisposeBag()
    
    var perView: UIView?
    
    let cashBack: OrderInfoBar = {
        let bar = OrderInfoBar()
        bar.titleLabel.text = LanguageHelper.getString(key: "EXPECTED_CASHBACK")
        bar.valueLabel.text = "$0.0"
        return bar
    }()
    
    var perExpanded: Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = lightSaperatorColor
        self.navigationItem.title = LanguageHelper.getString(key: "CASHBACK_DETAIL")
        setBackBarItem()
        
        initVM()
        
        cashBack.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: menuHeight)
        let cbTapGR = UITapGestureRecognizer()
        cbTapGR.addTarget(self, action: #selector(tapCashBack(_:)))
        cashBack.addGestureRecognizer(cbTapGR)
        self.view.addSubview(cashBack)
        
        var cashbackAmount: Double = 0
        if let vm = cashBackVM {            
            if let oi = orderId {
                vm.getOrderCashBack(id: oi).subscribe(onNext: { [unowned self] orderCB in
//                    print("cb!!\(orderCB)")
                    if let amount = orderCB.amountPaid, let strategy = orderCB.cashBackStrategy {
                        if let role = self.role {
                            if role.count > 0 {
                                let cdHeight: CGFloat = 20
                                self.perView = UIView()
                                self.perView?.frame = CGRect(x: 0, y: menuHeight, width: self.view.bounds.width, height: CGFloat(role.count) * cdHeight)
                                for i in 0...role.count - 1 {
                                    let perLabel = UILabel()
                                    perLabel.font = AppFont(size: 13)
                                    perLabel.textColor = UIColor.gray
                                    switch role[i] {
                                    case .customer:
                                        if strategy.percentageForCustomer != nil {
                                            perLabel.text = "\(LanguageHelper.getString(key: "CONSUMER_RATE"))：\(strategy.percentageForCustomer!)%"
                                        }
                                    case .manager:
                                        if strategy.percentageForManager != nil {
                                            perLabel.text = "\(LanguageHelper.getString(key: "MANAGER_RATE"))：\(strategy.percentageForManager!)%"
                                        }
                                    case .recommender:
                                        if strategy.percentageForRecommender != nil {
                                            perLabel.text = "\(LanguageHelper.getString(key: "RECOMMENDER_RATE"))：\(strategy.percentageForRecommender!)%"
                                        }
                                    }
                                    let textMaxSize = CGSize(width: self.view.bounds.width, height: cdHeight)
                                    let perSize = TextSize.textSize(text: perLabel.text!, font: perLabel.font, maxSize: textMaxSize)
                                    perLabel.frame = CGRect(x: self.view.bounds.width - perSize.width - 15, y: (cdHeight - perSize.height) / 2 + CGFloat(i) * cdHeight, width: perSize.width, height: perSize.height)
                                    self.perView?.addSubview(perLabel)
                                }
                            }
                            if role.contains(.customer) && strategy.percentageForCustomer != nil {
                                cashbackAmount += amount * strategy.percentageForCustomer! / 100
                            }
                            if role.contains(.manager) && strategy.percentageForManager != nil {
                                cashbackAmount += amount * strategy.percentageForManager! / 100
                            }
                            if role.contains(.recommender) && strategy.percentageForRecommender != nil {
                                cashbackAmount += amount * strategy.percentageForRecommender! / 100
                            }
                        }
                        self.cashBack.valueLabel.text = "$\(cashbackAmount)"
                        self.cashBack.layoutSubviews()
                    }
                    }, onError: { error in
                        if error != nil {
                            print(error)
                        }
                })
                .addDisposableTo(disposeBag)
            }
        }
    }
    
    func initVM() {
        let authManager = AuthManager.share
        if authManager.hasLogined() {
            if let token = authManager.getToken() as? String {
                cashBackVM = CashBackViewModel(token: token)
            }
        }
    }
    
    func tapCashBack (_ sender: UIGestureRecognizer) {
        if perExpanded {
            //收起
            UIView.animate(withDuration: 0.5, animations: { [unowned self] in
                self.cashBack.pointerLabel.transform = CGAffineTransform.identity
                if let pv = self.perView {
                    pv.removeFromSuperview()
                }
                }, completion: nil)
        } else {
            //展開
            UIView.animate(withDuration: 0.5, animations: { [unowned self] in
                self.cashBack.pointerLabel.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 2)
                if let pv = self.perView {
                    self.view.addSubview(pv)
                }
                }, completion: nil)
        }
        perExpanded = !perExpanded
    }
    
}
